package application.handlers;

import application.RequestHandler;
import application.UserLoggedManager;
import contracts.requests.LoginRequest;
import contracts.responses.LoginResponse;
import domain.entities.User;
import domain.services.UserDomainService;
import internal.InternalResult;
import io.netty.channel.Channel;
import util.ChannelHelper;

/**
 * 登录处理器
 *
 * @author wyl
 */
public class LoginHandler extends RequestHandler<LoginRequest, LoginResponse> {

    @Override
    public LoginResponse handle(LoginRequest loginRequest, Channel requestChannel) {
        UserDomainService userDomainService = UserDomainService.Instance;


        InternalResult loginResult = userDomainService.login(
                loginRequest.username,
                loginRequest.password);


        String token = "";
        boolean success = false;
        String errorMessage = "";
        //等录成功
        if (loginResult.isSuccess()) {
            User u = (User) loginResult.getData();
            InternalResult tokenBuildResult = userDomainService.buildUserToken(u);
            //构建token成功
            if (tokenBuildResult.isSuccess()) {
                //加入登录管理器
                UserLoggedManager.login(ChannelHelper.getConnId(requestChannel), u);
                token = tokenBuildResult.getData().toString();
                success = true;
            } else {
                errorMessage = tokenBuildResult.getErrorMessage();
            }
        } else {
            errorMessage = loginResult.getErrorMessage();
        }


        return new LoginResponse(
                success,
                ChannelHelper.getConnId(requestChannel),
                errorMessage, token);
    }
}
